﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Application.DTO;
using AutoMapper;
using Core;
using Core.Entities;
using Core.IPepositories;
using Microsoft.EntityFrameworkCore;

namespace Application
{
    public class DepartmentService : IDepartmentService
    {
        private readonly IDepartmentRepository _repositiry;
        private readonly IMapper _mapper;
        private readonly IUnitOfWork _unitOfWork;

        public DepartmentService(IDepartmentRepository repository,IUnitOfWork unitOfWork, IMapper mapper)
        {
            _repositiry = repository;
            _mapper = mapper;
            _unitOfWork = unitOfWork;
        }

        public void Delete(Guid id)
        {
            _repositiry.Delete(id);
            _unitOfWork.Save();
        }

        public void DeleteBatch(List<Guid> ids)
        {
            _repositiry.Delete(t => ids.Contains(t.ID));
            _unitOfWork.Save();
        }

        public DepartmentDTO Get(Guid id)
        {
            return _mapper.Map<DepartmentDTO>(_repositiry.Get(id));
        }

        public List<DepartmentDTO> GetAllList()
        {
            var departments = _repositiry.GetList().OrderBy(t=>t.Code);

            return _mapper.Map<List<DepartmentDTO>>(departments);
        }

        public List<DepartmentDTO> GetDepartmentsByParent(Guid parentID, int startPage, int pageSize, out int rowCount)
        {
            var departments = _repositiry.LoadPageList(startPage, pageSize, out rowCount, it => it.ParentID == parentID, it => it.Code);
            return _mapper.Map<List<DepartmentDTO>>(departments.Include(nameof(Department.Manager)));
        }

        public bool InsertOrUpdate(DepartmentDTO dto)
        {
            var menu = _repositiry.InsertOrUpdate(_mapper.Map<Department>(dto));
            _unitOfWork.Save();
            return menu == null ? false : true;
        }
    }
}
